package com.zimin.cloud.system.biz.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zimin.cloud.mine.pojo.system.business.MenuBO;
import com.zimin.cloud.mine.pojo.system.view.MenuVO;
import com.zimin.cloud.system.biz.IMenuBiz;
import com.zimin.cloud.system.pojo.entity.Menu;
import com.zimin.cloud.system.service.IMenuService;
import com.zimin.cloud.system.service.impl.MenuServiceImpl;
import com.zimin.common.annotation.Biz;
import com.zimin.common.enums.Number;
import com.zimin.common.utils.BeanUtils;
import com.zimin.common.utils.ObjectUtils;
import com.zimin.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 菜单权限 业务对象
 * </p>
 *
 * @author zimin
 * @since 2021-12-30 11:05
 */
@Biz("menuBiz")
public class MenuBizImpl extends MenuServiceImpl implements IMenuBiz {

    @Autowired
    private IMenuService menuService;

    @Override
    public List<MenuVO> routes(MenuBO menuBO) {
        var menuVOList = menuService.listVO(null);
        return tree(menuVOList, Number.ZERO.getStrNum());
    }

    @Override
    public List<MenuVO> allRoutes(MenuBO menuBO) {
        var menuVOList = menuService.listVO(Wrappers.<Menu>lambdaQuery()
                .like(StringUtils.isNotEmpty(menuBO.getMenuName()), Menu::getMenuName, menuBO.getMenuName())
                .eq(ObjectUtils.isNotEmpty(menuBO.getStatus()), Menu::getStatus, menuBO.getStatus()));
        return ObjectUtils.isEmpty(menuVOList) ? menuVOList : tree(menuVOList, Number.ZERO.getStrNum());
    }

    @Override
    public boolean save(MenuBO menuBO) {
        return super.save(BeanUtils.coverClass(menuBO, Menu.class));
    }

    @Override
    public boolean updateById(MenuBO menuBO) {
        return super.updateById(BeanUtils.coverClass(menuBO, Menu.class));
    }


    /**
     * <p>获取分类树</p>
     *
     * @param menuVOList 原List
     * @param parent     上级父ID
     * @return java.util.List<com.zimin.cloud.mine.pojo.wiki.view.MenuVO>
     * @since 2021-11-24 16:55:59
     */
    private List<MenuVO> tree(List<MenuVO> menuVOList, String parent) {
        var childrenMap = menuVOList.stream()
                .collect(Collectors.groupingBy(MenuVO::getParentId));
        var children = childrenMap.get(parent);
        children.forEach(menuVO -> {
            var parentNodeId = menuVO.getId();
            var menuVoList1 = childrenMap.get(parentNodeId);
            if (ObjectUtils.isNotEmpty(menuVoList1)) {
                var tree = tree(menuVOList, parentNodeId);
                menuVO.setChildren(tree);
            }
        });
        return children;
    }

}
